from inspect import _void
from typing import Any
import xlsxwriter
import math


class ExcelUtil:
    @staticmethod
    def write_array(path: str, headers: list, rows: list) -> xlsxwriter.Workbook:
        """
        将数据结果写入Excel

        Args:
            path (str): 文件路径
            headers (list): 表头
            rows (list): 数据
        """
        workbook = xlsxwriter.Workbook(path)
        _ = ExcelUtil.write_array_wb(workbook, "Sheet1", headers, rows)
        workbook.close()
        return workbook

    @staticmethod
    def write_array_wb(
        workbook: xlsxwriter.Workbook, name: str, headers: list, rows: list
    ) -> xlsxwriter.Workbook.worksheet_class | Any:
        """
        将数据结果写入Excel

        Args:
            path (str): 文件路径
            headers (list): 表头
            rows (list): 数据
        """
        sheet = workbook.add_worksheet(name)
        for i in range(len(headers)):
            sheet.write(f"{ExcelUtil.to_column_name(i+1)}1", headers[i])

        row_index = 1
        for row in rows:
            row_index += 1
            for i in range(len(row)):
                sheet.write(f"{ExcelUtil.to_column_name(i+1)}{row_index}", row[i])

        return sheet

    @staticmethod
    def to_column_name(index: int) -> str:
        """
        转化 index 到列名。
        比如： 1 -> A, 26 -> Z, 27 -> AA

        Args:
            index (int): one based index

        Returns:
            str: 返回的字符
        """
        col_name = ""
        quotient: int
        remainder: int
        quotient, remainder = divmod(index, 26)
        while True:
            if quotient == 0 and remainder == 0:
                return col_name

            if remainder == 0:
                remainder = 26
                quotient -= 1

            col_name = ExcelUtil.to_column_letter(remainder) + col_name
            quotient, remainder = divmod(quotient, 26)

    @staticmethod
    def to_column_letter(index: int) -> str:
        """
        转化 index 到字母。
        比如： 1 -> A, 26 -> Z

        Args:
            index (int): one based index

        Returns:
            str: 返回的字符
        """
        return chr(ord("A") + index - 1)
